import React, {useState} from "react"
import "./index.less"
import {appContext} from "context/app-context"
import {
  DesktopOutlined,
  ExclamationCircleOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SkinOutlined
} from '@ant-design/icons';

import {Divider, Dropdown, Form, Input, Menu, Modal, Progress} from 'antd'
import JSEncrypt from "jsencrypt";
import {withRouter} from "react-router"
import Theme from "./theme"
import KeyOutlined from "@ant-design/icons/lib/icons/KeyOutlined"
import {enterFullScreen, exitFullScreen} from "libs/fullscreen"
import {postParam, putJSON} from "../../../../shared/server"
import UserOutlined from "@ant-design/icons/lib/icons/UserOutlined"

import {avatarPath, Middle, PUBLIC_KEY, regex_password6, Strong, Weak} from "../../../../shared/project-config";

const inputSize = 'default'

const userMenu = ({logout, userInfo, history, changePassword}) => {
  return (
    <div className={'user-menu'}>
      <div>
        <div className={'user-info body-bg'}>
          <div className="header-user-avatar header-bg">
            <img src={`${avatarPath(userInfo.avatar)}`} style={{width: '60px', height: '60px'}}/>
            {/* <AvatarLoader src={`${userInfo.avatar}`} style={{width: '60px', height: '60px'}}/> */}
          </div>
          <div>
            <h3 className={'header-text'}>{userInfo.name || '匿名用户'}</h3>
            <div className={'role-names secondary-text'}>
              {userInfo.role}
            </div>
          </div>
        </div>
      </div>
      <Divider/>
      <Menu style={{width: '100%'}}>
        <Menu.Item key={'2'}>
          <div className={"header-menu-item"} onClick={changePassword}>
            <KeyOutlined/> 修改密码
          </div>
        </Menu.Item>
        <Menu.Divider/>
        <Menu.Item key={'3'}>
          <div className={"header-menu-item"} onClick={logout}>
            <LogoutOutlined/> 退出系统
          </div>
        </Menu.Item>
      </Menu>
    </div>
  )
}

const AppHeader = (props) => {

  const {
    context,
    history
  } = props
  const {menuCollapsed, setMenuCollapsed, userInfo} = context

  const [fullScreen, $fullScreen] = useState(false)
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();

  //切换全屏
  const toggleFullScreen = () => {
    if (fullScreen) {
      exitFullScreen()
      $fullScreen(false)
    } else {
      enterFullScreen()
      $fullScreen(true)
    }
  }

  const logout = () => {
    Modal.confirm({
      title: '退出',
      content: '确定退出登录吗？',
      icon: <ExclamationCircleOutlined/>,
      onOk: () => {
        postParam('/management/logout', {})
          .then((data) => {
            props.history.push('/login')
          })
      }
    })
  }

  const changePassword = () => {
    setVisible(true);
  }
  const [passwordValidate, setPasswordValidate] = useState(0);

  const handlePassword = (event) => {
    const value = event.target.value;
    if (!value && value.length <= 6) setPasswordValidate(0);
    if (Strong.test(value)) setPasswordValidate(100);
    if (Middle.test(value)) setPasswordValidate(75);
    if (Weak.test(value)) setPasswordValidate(50);
  }

  const resetPassword = () => {
    form.validateFields().then((values) => {
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(PUBLIC_KEY);
        const oldSecret = encrypt.encrypt(values.oldPassword);
        const passwordSecret = encrypt.encrypt(values.newPassword);
        const postData = {
          encrypt: true,
          oldPassword: oldSecret,
          newPassword: passwordSecret,
        }
        putJSON("/management/account/admin/changePassword", postData).then(result => {
          if (result) {
            setVisible(false);
            Modal.error({
              title: '提示',
              content: (
                <div>
                  修改密码后需要重新登录...
                </div>
              ),
              onOk: () => {
                history.push("/login");
              }
            })
          }
        })
      }
    ).catch(info => {
      console.log(info, "error info")
    })
  }
  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  const layout = {
    labelCol: {span: 6},
    wrapperCol: {span: 16},
  };

  return (
    <div className={"zr-app-header"}>
      <Modal
        destroyOnClose
        title="修改密码"
        visible={visible}
        onOk={resetPassword}
        onCancel={() => setVisible(false)}
      >
        <Form
          {...layout}
          form={form}
          name="basic"
          onFinish={resetPassword}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="旧 密 码"
            name="oldPassword"
            validateFirst={true}
            rules={[{required: true, message: '旧密码必须填写',}]}
          >
            <Input.Password prefix={<KeyOutlined/>} size={inputSize} placeholder="请输入旧密码"/>
          </Form.Item>
          <Form.Item
            label="新 密 码"
            name="newPassword"
            validateFirst={true}
            rules={[
              {required: true, message: '新密码必须填写',},
              {pattern: regex_password6, message: "6-20位字母(至少包含一个字母和数字)"}
            ]}
          >
            <div>
              <Input.Password prefix={<KeyOutlined/>} size={inputSize} placeholder="请输入新密码" onChange={handlePassword}/>
              <div style={{width: "100%", display: "flex", alignItems: "center", marginTop: 5}}>
                <span style={{marginRight: 5}}>密码强度检测:</span>
                <Progress percent={passwordValidate}
                          strokeWidth={20}
                          showInfo={false}
                          steps={3} strokeColor={
                  passwordValidate === 50
                    ? "#ff4d4f"
                    : passwordValidate === 75
                    ? "orange"
                    : "#52c41a"}/>
              </div>
            </div>
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="confirm"
            dependencies={['newPassword']}
            validateFirst={true}
            rules={[
              {
                required: true,
                message: '确认密码必须填写',
              },
              ({getFieldValue}) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次密码不一致');
                },
              }),
            ]}
          >
            <Input.Password prefix={<KeyOutlined/>} size={inputSize} placeholder="请确认新密码"/>
          </Form.Item>
        </Form>
      </Modal>
      <div className={'header-menu-fold header-button'} onClick={() => setMenuCollapsed(!menuCollapsed)}>
        {
          menuCollapsed
            ? <MenuUnfoldOutlined/>
            : <MenuFoldOutlined/>
        }
      </div>

      <div className="header-button-box">

        <Dropdown overlay={userMenu({logout, userInfo, history, changePassword})} placement="bottomRight"
                  trigger={['click']}>
          <div className={"header-button"}>
            <UserOutlined/>
          </div>
        </Dropdown>

        <div className={"header-button"} onClick={toggleFullScreen}>
          <DesktopOutlined/>
        </div>

        <Dropdown overlay={<Theme/>} placement="bottomCenter" trigger={['click']}>
          <div className={"header-button"}>
            <SkinOutlined/>
          </div>
        </Dropdown>
      </div>
    </div>
  )
}

export default appContext(withRouter(AppHeader))